package com.ipay.wechat.util;

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import com.ipay.redis.JedisExecutor;
import com.ipay.wechat.component.Wechat;
import com.ipay.wechat.pojo.AccessToken;
import com.ipay.wechat.pojo.UserWechatInfo;
import com.ipay.wechat.service.TradeRecordService;
import com.ipay.wechat.service.UserWechatInfoService;

import net.sf.json.JSONObject;

@Component
public class WechatUtil {
	private Logger logger=LoggerFactory.getLogger(getClass());
	@Autowired
	private JedisExecutor jedies;
	@Autowired
	private Wechat wechat;
	@Autowired
	private TradeRecordService tradeRecordService;

	public void managerUserInfo(Wechat wechat, String openid, UserWechatInfoService uwiService){
		try {
			//String access_token=jedies.getValue(JedisKeyPrefix.JEDIS_KEY_PREFIX_WECHAT_TOKEN, "access_token");
			//logger.info("access_tokemn==="+jedies.getValue(JedisKeyPrefix.JEDIS_KEY_PREFIX_WECHAT_TOKEN, "access_token"));
			AccessToken accessToken = AccessTokenUtil.freshAccessToken(wechat);
			String access_token = accessToken.getAccess_token();
			String result = ExecuteWeChat.getBaseUserInfo(access_token, openid); // 获取用户的微信信息
			logger.info("用户信息===" + result);	
			JSONObject json=JSONObject.fromObject(result);
			int count=uwiService.findCountOneWXUI(openid);
			logger.info("count ==="+count);
			UserWechatInfo wechatInfo=new UserWechatInfo();
			wechatInfo.setCity(json.getString("city"));
			wechatInfo.setCountry(json.getString("country"));
			wechatInfo.setGroupid(Integer.parseInt(json.getString("groupid")));
			wechatInfo.setHeadimgurl(json.getString("headimgurl"));
			logger.info("nickname==="+URLEncoder.encode(json.getString("nickname"),"utf-8"));
			wechatInfo.setNickname(URLEncoder.encode(json.getString("nickname"),"utf-8"));
			wechatInfo.setOpenid(json.getString("openid"));
			wechatInfo.setProvince(json.getString("province"));
			wechatInfo.setRemark(json.getString("remark"));
			wechatInfo.setSex(json.getString("sex"));
			wechatInfo.setSubscribe(Integer.parseInt(json.getString("subscribe")));
			if(count==0){   //该用户第一次关注此公众号
				uwiService.addWechatUserInfo(wechatInfo);
			}else{
				uwiService.updateWechatUserInfo(wechatInfo);
			}
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
	}
	@Deprecated
	public void saveUserInfo(String openid, UserWechatInfoService uwiService){
		try {
			String access_token = tradeRecordService.getAccessToken();
			String result = ExecuteWeChat.getBaseUserInfo(access_token, openid); // 获取用户的微信信息
			JSONObject json=JSONObject.fromObject(result);
			
			UserWechatInfo wechatInfo=new UserWechatInfo();
			wechatInfo.setCity(json.getString("city"));
			wechatInfo.setCountry(json.getString("country"));
			wechatInfo.setGroupid(Integer.parseInt(json.getString("groupid")));
			wechatInfo.setHeadimgurl(json.getString("headimgurl"));
			wechatInfo.setNickname(URLEncoder.encode(json.getString("nickname"),"utf-8"));
			wechatInfo.setOpenid(json.getString("openid"));
			wechatInfo.setProvince(json.getString("province"));
			wechatInfo.setRemark(json.getString("remark"));
			wechatInfo.setSex(json.getString("sex"));
			wechatInfo.setSubscribe(Integer.parseInt(json.getString("subscribe")));
			uwiService.addWechatUserInfo(wechatInfo);
		} catch (Exception e) {
			logger.info(e.getMessage());
			e.printStackTrace();
		}
		
	}
	public Map<Integer, String> uploadImg(MultipartFile[] file, String realPath, String mobile) throws IllegalStateException, IOException {
		// TODO Auto-generated method stub
		String path=null;// 文件路径
        String type=null;// 文件类型

		Map<Integer, String> map = new HashMap<Integer, String>();
        if(file != null){
			for (int i = 0; i < file.length; i++) {
           	 String fileName = file [i] .getOriginalFilename(); 
           	 MultipartFile myfile = file [i];
				if (fileName != null) {
					type = fileName.indexOf(".") != -1 ? fileName.substring(
							fileName.lastIndexOf(".") + 1, fileName.length())
							: null;
					if (type != null) {// 判断文件类型是否为空
						if ("GIF".equals(type.toUpperCase())
								|| "PNG".equals(type.toUpperCase())
								|| "JPG".equals(type.toUpperCase())) {
							// 项目在容器中实际发布运行的根路径
							// 自定义的文件名称
							String trueFileName = mobile + i + "." + type;
							logger.info("trueFileName" + trueFileName);
							// 设置存放图片文件的路径
							path = realPath
									+ System.getProperty("file.separator")
									+ trueFileName;
							logger.info("存放图片文件的路径:" + path);
							map.put(i, path);
							// 转存文件到指定的路径
							myfile.transferTo(new File(path));
							logger.info("文件成功上传到指定目录下");
						} else {
							logger.info("不是我们想要的文件类型,请按要求重新上传");
							return null;
						}
					} else {
						logger.info("文件类型为空");
						return null;
					}
				}
           }
        }
		return null;
	}
	
	
	
	

}
